#include <iostream>
#include <string>
#include <cstring>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const uint16_t port = 8080;
int main()
{
    socket listensock = sock(AF_INET, SOCK_STREAM, 0);
    if (listensock < 0)
    {
        cout << "sock error" << endl;
        return 1;
    }

    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;
    if (bind(listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
    {
        cout << "bind error" << endl;
        return 2;
    }

    if (listen(listensock, 5) < 0)
    {
        cout << "listen error" << endl;
        return 3;
    }

    while (1)
    {
        struct sockaddr_in peer;
        socklen_t lenth = sizeof(peer);
        int new_sock = accept(listensock, (struct sockaddr *)&peer, &lenth);
        if (new_sock < 0)
        {
            continue;
        }

        for (;;)
        {
            char buf[1024];
            memset(buf, 0, sizeof(buf));
            size_t s = read(new_sock, buf, sizeof(buf) - 1);
            if (s > 0)
            {
                buf[s] = 0;
                cout << "client says: " << buf << endl;
                string echo;
                cout << "echo" << endl;
                cin >> echo;
                write(new_sock, echo.c_str(), echo.size());
            }
            else if(s==0)
            {
                cout<<"client quit..."<<endl;
                break;
            }
            else
            {
                cout<<read error<<endl;
                break;
            }
        }
    }

    return 0;
}